/*
 * @brief
 * @author li yong (DogLee)
 * @email 20162439@qq.com
 * @version 1.0
 * @date 2018-08-03 09:16:49
 */
#include "logmanager.h"
#include "logappenderterminal.h"
#include "logappenderfile.h"
#include "logappendernet.h"

#include <QMutex>
#include <QThread>

#include "application.h"
#include "pubsubobject.h"

Q_GLOBAL_STATIC(QMutex, mutex)


LogManager *LogManager::pInstance = nullptr;

LogManager::LogManager()
{
    ILogAppender* log;

    QThread *th = new QThread();
    th->setObjectName("logmanager");
    log = new LogAppenderTerminal();
    logAppenders.append(log);
    TestThreadIsLocked(log);
    log->moveToThread(th);

    log = new LogAppenderFile();
    logAppenders.append(log);
    log->moveToThread(th);

    log = new LogAppenderNet();
    logAppenders.append(log);
    log->moveToThread(th);

    th->start();
    th->setObjectName("log_manager");
}

LogManager::~LogManager()
{

}

void LogManager::appendMessage(const DebugMessage &message)
{
    foreach (auto log, logAppenders)
        log->append(message);
}

void LogManager::dump()
{
    foreach (auto log, logAppenders)
        log->dump();
}

LogManager *LogManager::instance()
{
    if (pInstance == nullptr)
    {
        QMutexLocker locker(mutex());
        if (pInstance == nullptr)
        {
            pInstance = new LogManager();
        }
    }

    return pInstance;
}
